package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.form.service.impl.ScriptImpl;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.expimp.CustomExcelReader;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AbstractImpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WQbdDpaInfo;
import com.ccp.dev.qbdms.service.WCustomColumnsService;
import com.ccp.dev.qbdms.service.WQbdDpaInfoService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.service.DictionaryService;
import com.ccp.dev.workflow.service.ProcessRunService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * DPA 信息操作处理控制器
 * 
 * @author zzy
 * @date 2020-07-06 09:12:57
 */
@Controller
@Action(customModel = "DPA")
@RequestMapping("/qbdms/wQbdDpaInfo")
public class WQbdDpaInfoController extends SysBaseController{
	@Resource
	private WQbdDpaInfoService wQbdDpaInfoService;
    @Resource
    private ProcessRunService processRunService;
    @Resource
    private ScriptImpl scriptImpl;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private WCustomColumnsService wCustomColumnsService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: zzy
     * @date: 2020-07-06 09:12:57
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到DPA首页", exectype = "页面跳转日志")
    public String viewList(Model model,HttpServletRequest request) {
        wCustomColumnsService.addCustomCols(request);
        model.addAttribute("syslev", BaseUtil.getCurrentSystemLevel());
        model.addAttribute("currentUserId", scriptImpl.getCurrentUserId());
        return "wQbdDpaInfo/list";
    }

    /**
    * 功能描述: 附带检索条件的分页查询
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: zzy
    * @date: 2020-07-06 09:12:57
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询DPA",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        queryFilter.put("orderField", "createTime");
        queryFilter.put("orderSeq", "desc");
        queryFilter.put("belongdeptname", BaseUtil.getCurrentTenOrgCodePath() + "%");
        queryFilter.put("secret", scriptImpl.getCurrentUser().getPrivacyLevel());

        //2020/7/28 zzy 增加状态码过滤
        ZhiLiangConst.addQueryFilter(queryFilter);

        //分页数据
        List<WQbdDpaInfo> pageDatas = wQbdDpaInfoService.queryList(queryFilter);
        // 试验结论
        List<Dictionary> syjl = dictionaryService.getDicByNodeKey("dpasyjl", false);
        // 质量等级
        List<Dictionary> zldj = dictionaryService.getDicByNodeKey("dpazldj", false);

        for (WQbdDpaInfo pageData : pageDatas) {
            pageData.setReportStatusStr(ZhiLiangConst.getStatusStrByInt(pageData.getReportStatus()));
            for (Dictionary dictionary : syjl) {
                if (dictionary.getItemValue().equals(pageData.getDpaTestConclusion())) {
                    pageData.setDpaTestConclusion(dictionary.getItemName());
                }
            }
            for (Dictionary dictionary : zldj) {
                if (dictionary.getItemValue().equals(pageData.getQualityLevel())) {
                    pageData.setQualityLevel(dictionary.getItemName());
                }
            }
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        //替换组织机构名称
        ZhiLiangConst.showName(pageDatas);
        // 判断数据是否允许编辑
        ZhiLiangConst.isDataAllowEdit(pageDatas, false);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: zzy
     * @date: 2020-07-06 09:12:57
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到DPA新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        return "wQbdDpaInfo/add";
    }

    /**
    * 功能描述:  数据保存通用方法
    *
    * @param: wQbdDpaInfo 保存的对象
    * @return: java.lang.Object
    * @auther: zzy
    * @date: 2020-07-06 09:12:57
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存DPA数据",detail="<#if isAdd>新增<#else>编辑</#if>DPA数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if>")
    public Object save(@RequestBody WQbdDpaInfo wQbdDpaInfo) {
        String id = wQbdDpaInfo.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
            //新增操作
            wQbdDpaInfo.setId(ProjectUUIDUtils.getUUIDFor32());
            //处理通用字段
            ZhiLiangConst.addCommonFields(wQbdDpaInfo);
            //上报状态
            wQbdDpaInfo.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
            result = wQbdDpaInfoService.add(wQbdDpaInfo);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            ZhiLiangConst.updateCommonFields(wQbdDpaInfo);
            //修改操作
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", StructureModifyUtil.getModifyInfo(wQbdDpaInfoService.getOneById(id), wQbdDpaInfo));
            result = wQbdDpaInfoService.update(wQbdDpaInfo);
        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
    * 功能描述: 跳转到详情页面
    *
    * @return: java.lang.String
    * @auther: zzy
    * @date: 2020-07-06 09:12:57
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到DPA详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        String isClose = RequestUtil.getString(request, "isClose");
        modelMap.put("isClose", isClose);
        modelMap.put("id",id);
        return "wQbdDpaInfo/particulars";
    }

    /**
    * 功能描述: 根据主键id获取一条数据的通用查询方法
    *
    * @param: id 参数对象必须是"id"
    * @return: java.lang.Object
    * @auther: zzy
    * @date: 2020-07-06 09:12:57
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询DPA的一条数据",detail="根据主键id查询DPA的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdDpaInfo wQbdDpaInfo = wQbdDpaInfoService.getOneById(id);
        if (null == wQbdDpaInfo) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",wQbdDpaInfo);
    }

    /**
    * 功能描述: 根据主键ID删除数据的通用删除方法
    *
    * @param: id 参数名称必须是"id"
    * @return: java.lang.Object
    * @auther: zzy
    * @date: 2020-07-06 09:12:57
    */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除DPA数据",exectype = "删除日志",detail="删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) {
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail("delete.failure.message");
        }
        //判断是否允许删除
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdDpaInfo data = wQbdDpaInfoService.getOneById(key);
            if (Objects.nonNull(data.getReportStatus())
                    && !ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED.equals(data.getReportStatus())
                    && !ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED.equals(data.getReportStatus())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只允许删除待上报和待报集团的数据");
            }
            if (!userId.equals(data.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
        }

        int result = wQbdDpaInfoService.delByIdArray(id.split(","));
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
    * 功能描述: 跳转到导入页面
    *
    * @return: java.lang.String
    * @auther: hw
    * @date: 2019-12-25 19:21:40
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description="跳转到DPA导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdDpaInfo/import";
    }

    /**
    * 功能描述: 导出DPA数据信息
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: zzy
    * @date: 2020-07-06 09:12:57
    */
    @RequestMapping("/exportData")
    @Action(description="导出DPA数据信息",detail="导出DPA数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{

        SysAuditThreadLocalHolder.putParamerter("success",false);
        String[] id = RequestUtil.getStringAryByStr(request,"id");
        QueryFilter queryFilter = new QueryFilter(request,false);
        queryFilter.put("orderField", "createTime");
        queryFilter.put("orderSeq", "desc");
        queryFilter.put("belongdeptname", BaseUtil.getCurrentTenOrgCodePath() + "%");
        queryFilter.put("secret", scriptImpl.getCurrentUser().getPrivacyLevel());
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter,id);
        List<WQbdDpaInfo> datalist = wQbdDpaInfoService.queryAll(queryFilter);
        if(datalist.isEmpty()){
            datalist.add(new WQbdDpaInfo());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request,response,datalist,dataArray,"DPA信息", AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success",true);
    }

    /**
    * 导入资源文件
    * @param request
    * @param response
    * @throws Exception
    */
    @RequestMapping("/importData")
    @ResponseBody
    public Object importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{

        SysAuditThreadLocalHolder.putParamerter("success",false);
        MultipartFile multipartFile = request.getFile("file");
        TableEntity excelEntity = new CustomExcelReader().readFile(multipartFile.getInputStream());

        Map<String, Object> map = new AbstractImpUtil() {
            @Override
            public AbstractImpUtil.ReturnType customValidation(String fieldName, String fieldValue) {
                ReturnType returnType = null;
                if (fieldName.equals("actualNumOfSamples")) {
                    returnType = new ReturnType();
                    if (StringUtil.isEmpty(fieldValue)) {
                        returnType.setMsg("实际抽样数量必填!");
                        return returnType;
                    }
                    fieldValue=fieldValue.replaceAll(",", "");
                    try {
                        Integer.valueOf(fieldValue);
                        returnType.setNewValue(fieldValue);
                    }catch (NumberFormatException en){
                        returnType.setMsg("实际抽样数量值错误!");
                        return returnType;
                    }
                }
                return returnType;
            }
        }.reverseModels(excelEntity, WQbdDpaInfo.class);
        String msg = map.get("msg").toString();
        List<WQbdDpaInfo> list = (List<WQbdDpaInfo>)map.get("instList");

        if(StringUtil.isEmpty(msg)){
            wQbdDpaInfoService.addImportData(list);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("dataSource.importXml.success");
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail(msg);
        }
    }


    /**
     * 查询上报的信息
     *
     * @param request
     * @param id
     * @param tableName
     * @return
     */
    @RequestMapping("/reportList")
    @ResponseBody
    public Object reportList(HttpServletRequest request, @RequestParam("id") String id, @RequestParam("tableName") String tableName) throws IllegalAccessException {
        //业务数据
        List<WQbdDpaInfo> reportList = wQbdDpaInfoService.reportList(id, tableName);

        SysAuditThreadLocalHolder.putParamerter("success", true);
        // 试验结论
        List<Dictionary> syjl = dictionaryService.getDicByNodeKey("dpasyjl", false);
        // 质量等级
        List<Dictionary> zldj = dictionaryService.getDicByNodeKey("dpazldj", false);

        for (WQbdDpaInfo data : reportList) {
            for (Dictionary dictionary : syjl) {
                if (dictionary.getItemValue().equals(data.getDpaTestConclusion())) {
                    data.setDpaTestConclusion(dictionary.getItemName());
                }
            }
            for (Dictionary dictionary : zldj) {
                if (dictionary.getItemValue().equals(data.getQualityLevel())) {
                    data.setQualityLevel(dictionary.getItemName());
                }
            }
        }
        //替换组织机构名称
        ZhiLiangConst.showName(reportList);
        return getResultDataSuccess("options.success", reportList);
    }


    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @param request
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description = "跳转到DPA信息导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdDpaInfo.class);
        modelMap.put("tableInfo", jsonObject.toString());
        return "expImp/add";
    }
}
